
pd<-paste(wd, "/Figures/Figures_Output/",sep="")


library("png")

thumbnails <- function(x, y, images, width = 0.1*diff(range(x)), 
                       height = 0.1*diff(range(y))){
  images <- replicate(length(x), images, simplify=FALSE)
  stopifnot(length(x) == length(y))
  
  for (ii in seq_along(x)){
    rasterImage(images[[ii]], xleft=x[ii] - 0.5*width,
                ybottom= y[ii] - 0.5*height,
                xright=x[ii] + 0.5*width, 
                ytop= y[ii] + 0.5*height, interpolate=FALSE)
  }
}

stabs<-read.csv(file="stability_coeff_se.csv")[,1:3]




stabs<-stabs[order(stabs$estimate),]

pdf(file=paste(pd,"stability_coef_plot.pdf",sep=""), 12, 9)


par(mar=c(3,4,2,1))

plot(1:nrow(stabs),stabs[,2],type="n",axes=F,xlab="",ylab="")


grid()


mtext("Relative Elite Turnover Under Democracy",font=2,line=.5,cex=1.75)




text(seq(1,151,by=2), par("usr")[3]-.065, labels = as.character(stabs[seq(1,151,by=2),1]), srt = -60, xpd = TRUE,cex=.45)
text(seq(2,151,by=2), par("usr")[3]-.065, labels = as.character(stabs[seq(2,151,by=2),1]), srt = -60, xpd = TRUE,cex=.45)

axis(1,at=1:nrow(stabs),labels=F,cex.axis=.5,srt=45)
#axis(2,at=seq(-1,1,by=.25),line=-1)




for(i in 1:nrow(stabs)){
  
  
  
  lines(c(i,i), c(stabs$estimate[i] + 1.67*stabs$std_error[i], stabs$estimate[i] - 1.67*stabs$std_error[i]   ) , col="light grey")
  
  
  
}



lines(c(-1,151),c(0,0),lty=2,col="red")




points(1:nrow(stabs),stabs[,2],pch=16,cex=.5,col="black")





china_flag <- readPNG("china_flag.png")


thumbnails(x=151,y=stabs[151,2],china_flag,width=7,height=.075)

#dprk_flag <- readPNG("dprk_flag.png")

#thumbnails(x=150,y=stabs[150,2],dprk_flag,width=5,height=.075)


india_flag <- readPNG("indian_flag.png")

thumbnails(x=5,y=stabs[5,2],india_flag,width=7,height=.075)


#lines(c(-8,-8),c(-.7,.7))

axis(2,at=c(.72),labels=c("High"),tick=F,cex.axis=.75,font=2,las=2,pos=-9)
axis(2,at=c(.695),labels=c("Turnover"),tick=F,cex.axis=.75,font=2,las=2,pos=-5.5)
axis(2,at=c(.665),labels=c("In Democracy"),tick=F,cex.axis=.75,font=2,las=2,pos=-1)




axis(2,at=c(-.72+.05),labels=c("In Democracy"),tick=F,cex.axis=.75,font=2,las=2,pos=-1)
axis(2,at=c(-.695+.05),labels=c("Turnover"),tick=F,cex.axis=.75,font=2,las=2,pos=-5.5)
axis(2,at=c(-.665+.05),labels=c("Low"),tick=F,cex.axis=.75,font=2,las=2,pos=-9.5)




u <- par("usr") 

axis(2,lwd=.00,lwd.ticks=1,line=-.75)


arrows(u[1]+2.5, u[3], u[1]+2.5, u[4], code = 2, xpd = TRUE,lwd=1.5,length=.125)
arrows(u[1]+2.5, u[4], u[1]+2.5, u[3], code = 2, xpd = TRUE,lwd=1.5,length=.125)



dev.off()
